﻿using System;
using System.Data;
using System.Text;
using WeifenLuo.WinFormsUI.Docking;
using System.Windows.Forms;
using CoreScanner;
using System.Xml;
using System.Collections;

namespace docmgr.WinForm
{
    public partial class _MainForm : Form
    {
        private bool isclose = false;
        static CoreScanner.CCoreScannerClass cCoreScannerClass;

    
        public _MainForm()
        {
            InitializeComponent();

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

            try
            {
                openScanner();
            }
            catch(Exception ex1)
            {
                MessageBox.Show(ex1.StackTrace);
            }
            toolStripStatusLabel1.Text = "文件收发管理系统 当前用户：" + (String)Common.curUser.Rows[0]["Name"];


            String sqlStr = "SELECT	a.Code FROM	[dbo].[User] AS u LEFT JOIN [PositionAothority] AS pa ON u.PositionID = pa.PositionID LEFT JOIN Authority a ON pa.AuthorityID = a.id WHERE	u.id  =" +Convert.ToInt32(Common.curUser.Rows[0]["ID"]);

            DataTable dt = SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0];
            ArrayList list = new ArrayList();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                list.Add(Convert.ToString(dt.Rows[i]["Code"]));
            }

            /**
             EditUser EditPositionAutority EditDocument EditPosition LookDocReadLog EditAutority EditDepartment
             */
            /*
            if (list.Contains("EditAutority"))
                treeView1.Nodes.Add("AuthorityList", "权限");
            if (list.Contains("EditDepartment"))
                treeView1.Nodes.Add("DepartmentList", "部门");
            if (list.Contains("LookDocReadLog"))
             treeView1.Nodes.Add("DocReadLogList", "文件记录");
            if (list.Contains("EditDocument"))
                treeView1.Nodes.Add("DocumentList", "文件");
            if (list.Contains("EditPosition"))
                treeView1.Nodes.Add("PositionList", "岗位");
            if (list.Contains("EditPositionAutority"))
                treeView1.Nodes.Add("PositionAothorityList", "岗位权限");
            if (list.Contains("EditUser"))
                treeView1.Nodes.Add("UserList", "用户");
            */

            TreeNode Node1 = new TreeNode("常用操作");
            TreeNode Node2 = new TreeNode("系统操作");
            treeView1.Nodes.Add(Node1);
            treeView1.Nodes.Add(Node2);

            treeView1.SelectedNode = Node1;
            if (list.Contains("LookDocReadLog"))
                treeView1.SelectedNode.Nodes.Add("DocReadLogList", "文件记录");
            if (list.Contains("EditDocument"))
                treeView1.SelectedNode.Nodes.Add("DocumentList", "文件");
            if (list.Contains("EditDocConcerned"))
                treeView1.SelectedNode.Nodes.Add("DocConcernedList", "文件收藏");

            treeView1.SelectedNode = Node2;

            if (list.Contains("EditAutority"))
                treeView1.SelectedNode.Nodes.Add("AuthorityList", "权限");
            if (list.Contains("EditDepartment"))
                treeView1.SelectedNode.Nodes.Add("DepartmentList", "部门");
            if (list.Contains("EditPosition"))
                treeView1.SelectedNode.Nodes.Add("PositionList", "岗位");
            if (list.Contains("EditPositionAutority"))
                treeView1.SelectedNode.Nodes.Add("PositionAothorityList", "岗位权限");
            if (list.Contains("EditUser"))
                treeView1.SelectedNode.Nodes.Add("UserList", "用户");

            if (list.Contains("EditDirectory"))
                treeView1.SelectedNode.Nodes.Add("DirectoryList", "字典");
            treeView1.ExpandAll();
            Common._Main = this;

            Common.sessionTimer.Interval = 3*60 * 1000;//设置为五分钟的过期时间。
            Common.sessionTimer.Tick += new EventHandler(TimerOnTick);


            string currentPath = AppDomain.CurrentDomain.BaseDirectory;
            string exepath = currentPath + "conf.ini";
            IniFile ini = new IniFile(exepath);

            String autologin = ini.ReadInivalue("自动登录", "autologin");

            if (autologin.Equals("true"))
            {
                自动登录ToolStripMenuItem.Checked = true;
            }//读取啊啊啊啊。能不能慢下来。
        }

        void  openScanner()
        {///打开相关端口
         ///对其进行处理
            try
            {
                //Instantiate CoreScanner Class
                cCoreScannerClass = new CCoreScannerClass();
                //Call Open API
                short[] scannerTypes = new short[1];//Scanner Types you are interested in
                scannerTypes[0] = 1; // 1 for all scanner types
                short numberOfScannerTypes = 1; // Size of the scannerTypes array
                int status; // Extended API return code
                cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
                // Subscribe for barcode events in cCoreScannerClass
                cCoreScannerClass.BarcodeEvent += new
                _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
                // Let's subscribe for events
                int opcode = 1001; // Method for Subscribe events
                string outXML; // XML Output
                string inXML = "<inArgs>" +
                    "<cmdArgs>" +
                    "<arg-int>1</arg-int>" + // Number of events you want to subscribe
                    "<arg-int>1</arg-int>" + // Comma separated event IDs
                    "</cmdArgs>" +
                    "</inArgs>";
                cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
                Console.WriteLine(outXML);
            }
            catch (Exception exp)
            {
                Console.WriteLine("Something wrong please check... " + exp.Message);
            }
        }

        void OnBarcodeEvent(short eventType, ref string pscanData)
        {
            string barcode = decode(pscanData);
            this.Invoke((MethodInvoker)delegate
            { 
                Common._Main.Visible = true;
                Common._Main.WindowState = FormWindowState.Maximized;
                PopWindow frm = new PopWindow();
                frm.code = barcode;
                frm.ShowDialog();
            
            });
        }

        string decode(string pscanData)
        {
            System.Diagnostics.Debug.WriteLine("Initial XML" + pscanData);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(pscanData);
            string barcode = xmlDoc.DocumentElement.GetElementsByTagName("datalabel").Item(0).InnerText;

            string strData = String.Empty;
            string[] numbers = barcode.Split(' ');

            foreach (string number in numbers)
            {
                if (String.IsNullOrEmpty(number))
                {
                    break;
                }

                strData += ((char)Convert.ToInt32(number, 16)).ToString();
            }

            Byte[] bytearray = new Byte[strData.Length];

            for(int i=0;i<strData.Length;i++)
            {
                bytearray[i] = Convert.ToByte(strData[i]);
            }
            string str = Encoding.UTF8.GetString(bytearray);

            return str;
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            string className = e.Node.Name;
            string windowTitle = e.Node.Text;

            if (className == "") return;
            //--
            Type objtp = this.GetType().Assembly.GetType("docmgr.WinForm." + className, false, false);
            //Object[] parameters = new Object[] { this, Common.AppPath };
            object myobj = System.Activator.CreateInstance(objtp);// 应该是一种反射
            AddDockWindow((DockContent)myobj, DockAreas.Document, 100, windowTitle, "");
        }


        #region 以下方法无需修改
        public void AddDockWindow(Control contrl, DockAreas DockingState, int width, string title, object CTag)
        {
            foreach (WeifenLuo.WinFormsUI.Docking.DockContent dockCon in this.dockPanel1.Contents)
            {
                if (dockCon.TabText == title)
                {
                    dockCon.Activate();
                    return;
                }
            }
            WeifenLuo.WinFormsUI.Docking.DockContent dockContent = (WeifenLuo.WinFormsUI.Docking.DockContent)contrl;
            dockContent.TabText = title;
            dockContent.DockAreas = DockingState;
            dockContent.Tag = CTag;
            dockContent.Show(this.dockPanel1);
        }


        private void MainFrom_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!isclose)
            {
                if (MessageBox.Show("确定要关闭本程序吗?", "确定退出程序", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    isclose = true;
                    Application.Exit();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void menu_Window_CloseCur_Click(object sender, EventArgs e)
        {
            Form activeMdi = ActiveMdiChild;
            activeMdi.Close();
        }

        private void menu_Window_CloseOther_Click(object sender, EventArgs e)
        {
            Form activeMdi = ActiveMdiChild;
            foreach (Form form in MdiChildren)
            {
                if (form != activeMdi)
                {
                    form.Close();
                }
            }
        }

        private void menu_Window_CloseAll_Click(object sender, EventArgs e)
        {
            foreach (Form form in MdiChildren)
            {
                form.Close();
            }
        }

        private void mnitem_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void tsBtnOpen_Click(object sender, EventArgs e)
        {
            mnitem_About_Click(null,null);
        }
        private void tsbtnExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确认要退出本程序吗？", "确认操作", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                isclose = true;
                Application.Exit();
            }
        }

        private void mnitem_About_Click(object sender, EventArgs e)
        {
            string str = @"";

            str = @"文件收发管理系统  by 706RFID";
            MessageBox.Show(str, "文件收发管理系统", MessageBoxButtons.OK, MessageBoxIcon.Question);
        }
        #endregion

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            PasswordModify pm = new PasswordModify();
            pm.ShowDialog();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void _MainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
                notifyIcon1.Visible = true;
            }
            else
            {
                this.Visible = true;
                notifyIcon1.Visible = false;
            }
        }

        private void _MainForm_Load(object sender, EventArgs e)
        {
            Type objtp = this.GetType().Assembly.GetType("docmgr.WinForm." + "DocReadLogList", false, false);
            //Object[] parameters = new Object[] { this, Common.AppPath };
            object myobj = System.Activator.CreateInstance(objtp);// 应该是一种反射
            AddDockWindow((DockContent)myobj, DockAreas.Document, 100, "文件记录", "");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            
            Console.WriteLine("正是江南好风景，落花时节又逢君" + " " + Common.sessionLogin);
        }


        void TimerOnTick(object sender, EventArgs e) 
        {
            Common.sessionLogin = false;
            Common.sessionTimer.Stop();
        }

        private void 打印偏移量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintOffset frm = new PrintOffset();
            frm.ShowDialog();

            Common.ReadOffset();
        }

        private void 自动登录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;
            string exepath = currentPath + "conf.ini";
            IniFile ini = new IniFile(exepath);

            if(自动登录ToolStripMenuItem.Checked==true)
            {
                ini.WriteInivalue("自动登录", "autologin", "true");
                ini.WriteInivalue("自动登录", "username", Program.userName);
                ini.WriteInivalue("自动登录", "password", Program._passWord);
            }
            else
            {
                ini.WriteInivalue("自动登录", "autologin", "false");
                ini.WriteInivalue("自动登录", "username", "");
                ini.WriteInivalue("自动登录", "password", "");
            }
        }
    }
}
